import store from '@/store';
import {Message} from 'element-ui';
import { MessageBox } from 'element-ui';

let webSocket = null
let webSocketToken = ''

function createWebSocket(){
    webSocket = null
    if('WebSocket' in window){
        webSocketToken = store.state.token
        let side = store.state.side
        let token = webSocketToken
        if(webSocketToken !== ''){
            //const requestWsUrl = 'ws://192.168.1.28:8090/webapp/socket?side=' + side + '&token=' + token
            const requestWsUrl = 'ws://192.168.1.28:8090/webapp/socket?side=' + side
            //const requestWsUrl = `ws://192.168.1.28:8090/webapp/socket?side=web&token=${token}`
            webSocket = new WebSocket(requestWsUrl)
            webSocket.onopen = function(){
                console.log(token,'------连接建立成功---')
                // heart()
                // let heart = null
                // heart = setTimeout(() => {
                //     webSocket.send('ping')
                // },30000)
            }
            webSocket.onmessage = function(e){
                // 数据接收JSON转JS
                //this.data = JSON.parse(e.data)
                let data = e.data
                console.log(data)
                data = JSON.parse(e.data)
                let uplinkData = ''
                uplinkData = `${data.description}`
                store.state.upData = uplinkData
                store.state.upDataType = data.type
            }
        }
    }
    else{
        console.log('浏览器不支持webSocket')
    }
}
function reconnect(){
    createWebSocket()
}
////心跳包
// function heart(){
//     let timeoutObj = null
//     let serverTimeoutObj = null
//     let timeout = 3000
//     timeoutObj && clearTimeout(timeoutObj);
//     serverTimeoutObj && clearTimeout(serverTimeoutObj);
//     timeoutObj = setTimeout(function(){
//         //这里发送一个心跳，后端收到后，返回一个心跳消息
//         if (webSocket.readyState == 1) { //如果连接正常
//             webSocket.send("ping");
//         } else{  //否则重连
//             reconnect(url)
//         }
//         serverTimeoutObj = setTimeout(function() {
//             //超时关闭
//             webSocket.close();
//         }, timeout );
//     }, timeout+ 3000)
// }
export function localStore(){
    if(sessionStorage.getItem('store')){
        store.replaceState(
            Object.assign(
                {},
                store.state,
                JSON.parse(sessionStorage.getItem('store'))
            )
        )
    }
    window.addEventListener('beforeunload',() => {
        sessionStorage.setItem('store',JSON.stringify(store.state))
    })
}
export function initWebSocket(url){
    let wsUrl = url
    createWebSocket(wsUrl)
}
export function closeWebSocket(){
    if(webSocket){
        webSocket.close()
        webSocket.onclose = function(e){
            console.log(store.state.token,'------断开连接')
        }
    }
}
